<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j con-box page-apply-return">
    <div
      v-if="showApplyRefund"
      class="box-tit"
    >
      {{ $t('applyReturn.applyAfterSales') }}
    </div>
    <div
      v-if="!showApplyRefund"
      class="box-tit"
    >
      {{ $t('applyReturn.viewAfterSales') }}
    </div>
    <!-- 提交售后申请 -->
    <div
      v-if="showApplyRefund"
      :class="['box-content','apply-return', 'apply-box', $t('language') === 'en'?'en':'']"
    >
      <!-- 退款商品 -->
      <div class="item apply-item apply-prod">
        <div class="tit">
          {{ $t('applyReturn.refundedProducts') }}：
        </div>
        <div class="goods-box">
          <div class="goods-info">
            <!-- 普通商品 -->
            <div
              v-for="(refundItem, index) in orderItem"
              :key="index"
              class="goods-item"
            >
              <div class="goods-con">
                <div class="goods-img">
                  <img-show :src="refundItem.pic" />
                </div>
                <div class="goods-text">
                  <div class="name">
                    {{ refundItem.prodName }}
                  </div>
                  <div class="sku">
                    {{ refundItem.skuName }}
                    <span class="num">×{{ refundItem.prodCount }}</span>
                  </div>
                </div>
              </div>
              <!-- 赠品：整单退款时展示赠品名称和数量 -->
              <div
                v-if="orderRefundParam.refundType === 1 && refundItem.giveawayList && refundItem.giveawayList.length"
                class="gift-name-list"
              >
                <div
                  v-for="item in refundItem.giveawayList"
                  :key="item.orderItemId"
                  class="gift-item"
                  @click="toProdDetail(item.prodId)"
                >
                  <span class="name">{{ '【' + $t('prodDetail.gift') + '】' + item.prodName }}</span>
                  <span class="num">{{ item.skuName || '' }} × {{ item.prodCount }}</span>
                </div>
              </div>
              <!-- / 赠品 -->
            </div>
          </div>
          <!-- 赠品：单个退款时展示赠品具体信息 -->
          <div
            v-if="orderRefundParam.refundType === 2 &&
              giveawayList &&
              giveawayList.length"
            class="goods-info"
          >
            <div
              v-for="(prod,index) in giveawayList"
              :key="prod.orderItemId"
              class="goods-item giveaways"
            >
              <div class="goods-img">
                <img-show
                  :src="prod.pic"
                  @handle-click="()=>toProdDetail(prod.prodId)"
                />
              </div>
              <div class="goods-text">
                <div
                  class="name"
                  @click="toProdDetail(prod.prodId)"
                >
                  {{ prod.prodName }}
                </div>
                <div class="sku">
                  <span class="gifts-icon">{{ $t('prodDetail.gift') }}</span>
                  <span class="sku-name">{{ prod.skuName }}</span>
                  <span class="num">× {{ prod.prodCount }}</span>
                  <span
                    v-if="orderRefundParam.refundType !== 1 && status !== 2"
                    class="del-btn"
                    @click="removeGiveaways(index)"
                  >
                    {{ $t('prodDetail.removeGiftBtn') }}
                  </span>
                </div>
                <div class="price">
                  ￥{{ prod.giveawayAmount }}
                </div>
              </div>
            </div>
          </div>
          <!-- / 赠品 -->
        </div>
      </div>

      <div class="item">
        <div class="tit">
          {{ $t('applyReturn.serviceType') }}：
        </div>
        <div
          :class="[
            'apply-item unchecked',
            orderRefundParam.applyType === 1 || status === 2 ? 'active' : '',
          ]"
          @click="returnType(1)"
        >
          {{ $t('applyReturn.refundsOnly') }}
        </div>
        <div
          v-if="status !== 2 && orderMold !== 1"
          :class="[
            'apply-item unchecked',
            orderRefundParam.applyType === 2 ? 'active' : '',
          ]"
          @click="returnType(2)"
        >
          {{ $t('applyReturn.returnsAndRefunds') }}
        </div>
      </div>
      <div
        v-if="status !== 2"
        class="item"
      >
        <div class="tit">
          {{ $t('applyReturn.cargoStatus') }}：
        </div>
        <div
          v-if="orderRefundParam.applyType === 1 && !needWriteOffs"
          :class="[
            'apply-item unchecked',
            orderRefundParam.isReceiver === 0 ? 'active' : '',
          ]"
          @click="goodsStatus(0)"
        >
          {{ $t('applyReturn.noGoodsReceived') }}
        </div>
        <div
          :class="[
            'apply-item unchecked',
            orderRefundParam.isReceiver === 1 ? 'active' : '',
          ]"
          @click="goodsStatus(1)"
        >
          {{ $t('applyReturn.receivedGoods') }}
        </div>
      </div>
      <div :class="['item', showSelectTips ? 'error' : '']">
        <div class="tit">
          <span class="asterisk">*</span>{{ $t('applyReturn.refundReason') }}：
        </div>
        <div class="retur-reason">
          <div
            class="reason-tit"
            @click="selectReason"
          >
            {{
              orderRefundParam.buyerReasonStr
                ? orderRefundParam.buyerReasonStr
                : $t('applyReturn.select')
            }}
          </div>
          <div
            v-if="showReasonOptions && orderRefundParam.isReceiver === 0"
            class="reason-select"
          >
            <!-- 未发货或未收到货退款原因 -->
            <div
              v-for="(reason, index) in refundPriReasonArray"
              :key="index"
              class="s-item"
              :data-reason="reason"
              :data-idx="index"
              @click="returnReason($event)"
            >
              {{ reason }}
            </div>
          </div>
          <div
            v-if="showReasonOptions && orderRefundParam.isReceiver === 1"
            class="reason-select"
          >
            <!-- 已发货退款原因 -->
            <div
              v-for="(reason, index) in refundProdReasonArray"
              :key="index"
              class="s-item"
              :data-reason="reason"
              :data-idx="index"
              @click="returnReason($event)"
            >
              {{ reason }}
            </div>
          </div>
        </div>
        <div
          v-if="showSelectTips"
          class="error-text"
        >
          {{ $t('applyReturn.pleaseSelectReason') }}
        </div>
      </div>
      <!-- 退货数量(无需核销的虚拟商品允许选择数量) -->
      <div
        v-if="
          ((orderRefundParam.applyType === 2 &&
            orderRefundParam.refundType === 2 &&
            totalRefundScore === 0) ||
            orderMold === 1) && showNumber
        "
        class="item"
      >
        <div class="tit">
          {{ $t('applyReturn.refundQuantity') }}：
        </div>
        <div
          v-if="orderMold === 1 && needWriteOffs && maxRefundPieces"
          class="counter-box"
        >
          <div class="max-refund-pieces">
            {{ maxRefundPieces }} 件
          </div>
        </div>
        <div
          v-else
          class="counter-box"
        >
          <span
            class="reduce"
            @click="changePordNum(-1)"
          >-</span>
          <input
            v-model="goodsNum"
            type="text"
            class="prod-num-int"
            :readonly="true"
          >
          <span
            class="increase"
            @click="changePordNum(+1)"
          >+</span>
        </div>
      </div>
      <!-- 退款金额 -->
      <div :class="['item', showAmountTips ? 'error' : '']">
        <div class="tit">
          <span class="asterisk">*</span>{{ $t('applyReturn.refundAmount') }}：
        </div>
        <a
          v-if="
            ((refundType === 1 ? orderItem.platformShareReduce > 0 : orderItem[0].platformShareReduce > 0) ||
              totalRefundScore > 0 ||
              orderRefundParam.refundType === 1) &&
              orderMold !== 1
          "
          class="unalterable"
          :title="$t('applyReturn.refundAmountModified')"
        >
          <span v-if="actualTotal && actualTotal > 0">￥{{ actualTotal }}</span>
          <span v-if="actualTotal > 0 && totalRefundScore > 0">+</span>
          <span v-if="totalRefundScore && totalRefundScore > 0">{{
            totalRefundScore + $t('applyReturn.points')
          }}</span>
        </a>
        <div
          v-else
          class="return-price"
        >
          <span class="prefix">￥</span>
          <input
            v-model.number="actualTotal"
            :disabled="orderRefundParam.refundType === 1 || (orderRefundParam.applyType == 1&&status!==3&&status!==5&&status!==2) || platformCouponAmount || memberAmount || totalRefundScore"
            type="text"
            class="text"
            maxlength="20"
            :placeholder="$t('applyReturn.pleaseEnterAmount')"
            @blur="resetActualTotal"
          >
          <span
            v-if="totalRefundScore"
            class="return-score"
          >+ {{ totalRefundScore }} {{ $t('applyReturn.points') }}</span>
        </div>
        <div class="price-des">
          {{ $t('applyReturn.maximumRefundable') }}
          <!-- 整单退款包含运费 -->
          <span v-if="refundAmount && refundAmount > 0">￥{{ refundType === 1 ? actualTotal : refundAmount }}</span>
          <span v-if="refundAmount > 0 && totalRefundScore > 0">+</span>
          <span v-if="totalRefundScore && totalRefundScore > 0">{{
            totalRefundScore + $t('applyReturn.points')
          }}</span>
          <span v-if="showTransfee && transfee > 0">
            <el-popover
              placement="top-start"
              title=""
              width="200"
              trigger="hover"
              :content="$t('applyReturn.refundBeforeShippingTips')"
            >
              <template #reference>
                <el-icon><WarningFilled /></el-icon>
              </template>
            </el-popover>
          </span>
        </div>
        <div
          v-if="showAmountTips"
          class="error-text"
        >
          {{ $t('applyReturn.correctRefundAmount') }}
        </div>
      </div>
      <div :class="['item', showMobileTips ? 'error' : '']">
        <div class="tit">
          {{ $t('applyReturn.mobileNumber') }}：
        </div>
        <div class="fillin-mobilenumber">
          <input
            v-model="orderRefundParam.buyerMobile"
            type="text"
            class="text mobilenum"
            maxlength="11"
            :placeholder="$t('applyReturn.mobileNumberTips')"
            @blur="resetMobileNumber"
          >
        </div>
        <div
          v-if="showMobileTips"
          class="error-text"
        >
          {{ $t('applyReturn.correctPhoneNumber') }}
        </div>
      </div>
      <div :class="['item', showBuyerDescErrTips ? 'error' : '']">
        <div class="tit">
          <span class="asterisk">*</span>{{ $t('applyReturn.refundInstructions') }}：
        </div>
        <textarea
          v-model="orderRefundParam.buyerDesc"
          class="shop-description"
          :placeholder="$t('applyReturn.refundInstructionsTips')"
          maxlength="200"
          @blur="checkBuyerDesc"
        />
        <div
          v-if="showBuyerDescErrTips"
          class="error-text"
        >
          {{ $t('applyReturn.refundInstructionsTips') }}
        </div>
      </div>
      <div class="item">
        <div class="tit">
          {{ $t('applyReturn.refundVoucher') }}：
        </div>
        <div>
          <mul-pic-upload
            v-model="orderRefundParam.photoFiles"
            :limit="5"
          />
          <div class="img-des">
            （ {{ $t('applyReturn.uploadFiveVouchers') }} ）
          </div>
        </div>
      </div>
      <div class="item">
        <div class="tit">
          &nbsp;
        </div>
        <a
          href="javascript:void(0);"
          class="btn"
          @click="applyRefund"
        >{{ $t('applyReturn.SubmitRequest') }}</a>
      </div>
    </div>
    <!-- /提交售后申请 -->

    <!-- 等待商家处理&&填写运单号 -->
    <div
      v-if="!showApplyRefund"
      class="box-content apply-return applied-box"
    >
      <!-- 等待商家处理 -->
      <div
        v-if="WaitProcessing"
        class="return-wait"
      >
        <div class="return-state">
          <div class="state">
            {{ $t('applyReturn.applicationTips1') }}
          </div>
        </div>
        <div class="return-tip">
          <div
            v-if="orderRefundParam.applyType !== 1"
            class="tip-item"
          >
            {{ $t('applyReturn.applicationTips2') }}
          </div>
          <div class="tip-item">
            {{ $t('applyReturn.applicationTips3') }}
          </div>
          <div
            v-if="orderRefundParam.applyType !== 1"
            class="tip-item"
          >
            {{ $t('applyReturn.applicationTips4') }}
          </div>
        </div>
        <div class="return-btn">
          <a
            v-if="returnDetail.isCancel"
            href="javascript:void(0);"
            class="btn-r"
            @click="cancelApply"
          >{{ $t('applyReturn.applicationTips5') }}</a>
          <!--
            修改退款金额：
            1、仅退款(applyTyp:1)：买家申请(returnMoneySts:1)状态下可以修改
            2、退货退款(applyTyp:2)：买家申请(returnMoneySts:1) ||
                                    卖家处理(returnMoneySts:2) ||
                                    买家发货(returnMoneySts:3)
                                    状态下可以修改
            3、整单退款(refundType:1)：不可修改
            4、isUsedPlatformReduce 是否使用了平台优惠 （是 则不可修改）
          -->
          <a
            v-if="returnDetail.refundType !== 1 &&
              ((returnDetail.applyType === 1 &&
                returnDetail.returnMoneySts === 1) ||
                (returnDetail.applyType === 2 &&
                  (returnDetail.returnMoneySts === 1 ||
                    returnDetail.returnMoneySts === 2 ||
                    returnDetail.returnMoneySts === 3))) &&
              !isUsedPlatformReduce"
            href="javascript:void(0);"
            class="btn-r"
            @click="modifyRefundAmount"
          >{{ $t('applyReturn.modifyRefundAmount') }}</a>
        </div>
      </div>

      <!-- 填写运单号 -->
      <div
        v-if="fillInLogistics"
        class="return-wait"
      >
        <div class="return-state">
          <div
            v-if="returnDetail.returnMoneySts === 2"
            class="state"
          >
            {{ $t('applyReturn.applicationTips6') }}
          </div>
          <div
            v-if="returnDetail.returnMoneySts === 3"
            class="state"
          >
            {{ $t('applyReturn.applicationTips7') }}
          </div>
        </div>
        <div class="return-tip">
          <div class="tip-item">
            {{ $t('applyReturn.applicationTips8') }}
          </div>
          <div class="tip-item">
            {{ $t('applyReturn.applicationTips9') }}
          </div>
        </div>
        <div class="shop-info">
          <div class="shop-name">
            {{ $t('applyReturn.consignee') }}：
            <span class="name">{{
              returnDetail.refundDelivery.receiverName
            }}</span>
            <span class="phone">{{
              returnDetail.refundDelivery.receiverMobile
            }}</span>
          </div>
          <div class="shop-address">
            {{ returnDetail.refundDelivery.receiverAddr }}
          </div>
          <div class="shop-address">
            {{ returnDetail.refundDelivery.senderRemarks }}
          </div>
        </div>
        <div
          v-if="returnDetail.returnMoneySts === 2"
          class="return-btn"
        >
          <a
            href="javascript:void(0);"
            class="btn-r"
            @click="writeLogisticsMsg"
          >{{ $t('applyReturn.fillLogisticsInformation') }}</a>
        </div>
        <div
          v-if="returnDetail.returnMoneySts === 3"
          class="return-btn"
        >
          <a
            href="javascript:void(0);"
            class="btn-r"
            @click="writeLogisticsMsg"
          >{{ $t('applyReturn.modifyLogisticsInformation') }}</a>
        </div>
      </div>

      <!-- 已同意但未发放退款 (仅退款)-->
      <div
        v-if="returnDetail.returnMoneySts === 2 && returnDetail.applyType === 1"
        class="return-wait"
      >
        <div class="return-state">
          <div class="state">
            {{ $t('applyReturn.applicationTips6-1') }}
          </div>
        </div>
        <div class="return-tip">
          <div class="tip-item">
            {{ $t('applyReturn.applicationTips6-1-1') }}
          </div>
        </div>
      </div>

      <!-- 退款详情 -->
      <div class="return-detail">
        <div class="detail-tit">
          {{ $t('applyReturn.refundDetails') }}
        </div>
        <div class="item prod-con-box">
          <div class="tit">
            {{ $t('applyReturn.refundedProducts') }}：
          </div>
          <div>
            <div
              v-for="(refundProd, index) in prodList"
              :key="index"
              class="prod-item"
            >
              <!-- 普通商品详情 -->
              <div
                class="goods-info"
                :class="{'pointer': refundProd.giveawayOrderItemId}"
                @click="toProdDetail(refundProd.prodId)"
              >
                <div class="goods-img">
                  <img-show :src="refundProd.pic" />
                </div>
                <div class="goods-text">
                  <div class="name">
                    {{ refundProd.prodName }}
                  </div>
                  <div class="sku">
                    <span
                      v-if="refundProd.giveawayOrderItemId"
                      class="gift-icon"
                    >{{ $t('prodDetail.gift') }}</span>
                    <span>{{ refundProd.skuName }}</span>
                  </div>
                  <div class="price-con">
                    <span
                      v-if="refundProd.giveawayOrderItemId"
                      class="pri"
                    >￥{{ toPrice(refundProd.giveawayAmount) }}</span>
                    <span
                      v-if="!refundProd.giveawayOrderItemId"
                      class="pri"
                    >￥{{ toPrice(refundProd.price) }}</span>&nbsp;&nbsp;
                    <span>×{{ refundProd.prodCount }}</span>
                  </div>
                </div>
              </div>
              <!-- 赠品 -->
              <div
                v-if="returnDetail.orderItems.length > 1 &&
                  refundProd.giveawayList &&
                  refundProd.giveawayList.length"
                class="gift-prod"
              >
                <div
                  v-for="giftItem in refundProd.giveawayList"
                  :key="giftItem.orderItemId"
                  class="gift-item"
                  @click="toProdDetail(giftItem.prodId)"
                >
                  <span class="name">【{{ $t('prodDetail.gift') }}】{{ giftItem.prodName }}</span>
                  <span class="num">×{{ giftItem.prodCount }}</span>
                </div>
              </div>
              <!-- / 赠品 -->
            </div>
          </div>
        </div>
        <div class="detail-con">
          <div class="det-box">
            <div class="item">
              <div class="tit">
                {{ $t('applyReturn.merchantName') }}：
              </div>
              <div class="return-text">
                {{ returnDetail.shopName }}
              </div>
            </div>
            <div class="item">
              <div class="tit">
                {{ $t('applyReturn.cargoStatus') }}：
              </div>
              <div
                v-if="isReceiverOfCach"
                class="return-text"
              >
                {{ [$t('applyReturn.noGoodsReceived'), $t('applyReturn.receivedGoods')][isReceiverOfCach?isReceiverOfCach:0] }}
              </div>
              <div
                v-else
                class="return-text"
              >
                {{ returnDetail.isReceiver? $t('applyReturn.receivedGoods') : $t('applyReturn.noGoodsReceived') }}
              </div>
            </div>
            <div class="item">
              <div class="tit">
                {{ $t('applyReturn.orderNumber') }}：
              </div>
              <div class="return-text">
                {{ returnDetail.orderNumber }}
              </div>
            </div>
            <div class="item">
              <div class="tit">
                {{ $t('applyReturn.refundAmount') }}：
              </div>
              <div class="return-text">
                <span v-if="returnDetail.orderAmount">￥{{ toPrice(returnDetail.refundAmount) }}</span>
                <span
                  v-if="returnDetail.refundScore && returnDetail.orderAmount"
                >+</span>
                <span v-if="returnDetail.refundScore">{{ returnDetail.refundScore }} {{ $t('applyReturn.points') }}</span>
              </div>
            </div>
            <div class="item">
              <div class="tit">
                {{ $t('applyReturn.applicationNumber') }}：
              </div>
              <div class="return-text">
                {{ returnDetail.goodsNum }}{{ $t('items') }}
              </div>
            </div>
            <div class="item error">
              <div class="tit">
                {{ $t('applyReturn.refundReason') }}：
              </div>
              <div class="return-text">
                {{ refundReasonArray[returnDetail.buyerReason] }}
              </div>
            </div>
          </div>
          <div class="det-box">
            <div class="item">
              <div class="tit">
                {{ $t('applyReturn.refundNumber') }}：
              </div>
              <div class="return-text">
                {{ refundSn }}
              </div>
            </div>
            <div class="item">
              <div class="tit">
                {{ $t('applyReturn.refundType') }}：
              </div>
              <div class="return-text">
                {{ ['', $t('applyReturn.refundsOnly'), $t('applyReturn.returnsAndRefunds')][returnDetail.applyType] }}
              </div>
            </div>
            <div class="item error">
              <div class="tit">
                {{ $t('applyReturn.transactionTime') }}：
              </div>
              <div class="return-text">
                {{ returnDetail.orderPayTime }}
              </div>
            </div>
            <div
              v-if="returnDetail.orderMold!==1"
              class="item"
            >
              <div class="tit">
                {{ $t('applyReturn.courierPostage') }}：
              </div>
              <div class="return-text">
                ￥{{ toPrice(transfee) }}
              </div>
            </div>
            <div class="item">
              <div class="tit">
                {{ $t('applyReturn.totalOrderPrice') }}：
              </div>
              <div class="return-text">
                <span v-if="returnDetail.orderAmount">￥{{ returnDetail.orderAmount }}</span>
                <span
                  v-if="returnDetail.refundScore && returnDetail.orderAmount"
                >+</span>
                <span v-if="returnDetail.refundScore">{{ returnDetail.refundScore }} {{ $t('applyReturn.points') }}</span>
              </div>
            </div>
            <div class="item">
              <div class="tit">
                {{ $t('applyReturn.refundInstructions') }}：
              </div>
              <div class="return-text">
                {{ returnDetail.buyerDesc }}
              </div>
            </div>
          </div>
        </div>
        <div
          v-if="photoFiles.length"
          class="item"
        >
          <div class="tit">
            {{ $t('applyReturn.refundVoucher') }}：
          </div>
          <el-image
            v-for="(pic, picIndex) in photoFiles"
            :key="pic"
            class="ref-img"
            :src="checkFileUrl(pic)"
            :initial-index="picIndex"
            :preview-src-list="photoFiles"
          />
        </div>
      </div>
    </div>
    <!-- /等待商家处理&&填写运单号 -->

    <!-- 弹窗 -->
    <div
      v-if="false"
      class="popup-mask"
    />
    <div
      v-if="false"
      class="popup-box"
    >
      <div class="tit">
        <div class="text">
          {{ $t('tips') }}
        </div>
        <div class="close" />
      </div>
      <div class="con">
        <div class="tip">
          <div class="tip-icon success" />
          <div class="tip-info">
            <div class="result">
              {{ $t('applyReturn.applicationTips10') }}
            </div>
            <div class="date">
              {{ $t('applyReturn.applicationTips11') }}
            </div>
            <div class="btns">
              <a
                href="javascript:void(0);"
                class="btn"
              >
                {{ $t('applyReturn.ViewAfterSalesDetails') }}
                <span class="arrow">&gt;&gt;</span>
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- /弹窗 -->

    <!-- 修改退款金额弹窗 -->
    <div
      v-if="isModifyRefundAmount"
      class="popup-mask"
    />
    <div
      v-if="isModifyRefundAmount"
      class="popup-box"
    >
      <div class="tit">
        <div class="text">
          {{ $t('applyReturn.modifyRefundAmount') }}
        </div>
        <div
          class="close"
          @click="isModifyRefundAmount = false"
        />
      </div>
      <div class="con modify-amount">
        <div class="int-box">
          <input
            v-model="modifyAmount"
            type="text"
            class="int"
            :placeholder="$t('applyReturn.pleaseEnterAmount')"
            @blur="handleAmountInput"
            @focus="handleAmountInput"
          >
          <div
            v-if="!refundAmountError"
            class="max-amount"
          >
            {{ $t('applyReturn.maximumRefundable') }}￥{{ maxRefundAmount }}
          </div>
          <div
            v-if="refundAmountError"
            class="error"
          >
            {{ modifyAmount && Number.parseFloat(modifyAmount) > Number.parseFloat(maxRefundAmount)
              ? `${$t('applyReturn.maximumRefundable')}￥${maxRefundAmount}，${$t('applyReturn.reEnter')}`
              : $t('applyReturn.pleaseEnterAmount') }}
          </div>
        </div>
        <div class="foot-btn">
          <span
            class="confirm"
            @click="requestModify"
          >{{ $t('login.confirmChanges') }}</span>
        </div>
      </div>
    </div>
    <!-- / 修改退款金额弹窗 -->

    <!-- 物流信息弹框 -->
    <write-logistics-info
      v-if="showAdd"
      :refund-sn="refundSn"
      :order-number="orderRefundParam.orderNumber"
      :refund-delivery="returnDetail.refundDelivery"
      :return-money-sts="returnDetail.returnMoneySts"
      @toggle-addr-pop="refreshChange"
    />
  </div>
</template>

<script setup>
import * as util from '@/utils/index.js'
import Big from 'big.js'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()

const showNumber = computed(() => {
  // 无需核销的虚拟商品使用平台优惠后不能修改数量
  if ((totalRefundScore.value > 0 || platformCouponAmount.value > 0 || memberAmount.value > 0) && orderMold.value === 1 && !needWriteOffs.value) {
    return false
  }
  return true
})

// 申请售后数据
const orderRefundParam = reactive({
  orderNumber: route.query.orderNumber, // 订单编号
  applyType: 1, // 申请类型(1:仅退款 2退款退货)
  isReceiver: 0, // 货物状态(1:已收到货 0:未收到货)
  buyerReason: '', // 申请原因(下拉选择)
  buyerMobile: '', // 手机号
  buyerDesc: '', // 备注说明
  photoFiles: '', // 凭证图片列表
  refundType: Number(route.query.refundType), // 退款单类型（1:整单退款,2:单个物品退
  orderItemId: route.query.orderItemId, // 订单项ID（单个物品退款时使用）
  giveawayItemIds: [] // 赠品id数组
})

//  退款原因（已收到货）
const refundProdReasonArray = computed(() => {
  return [
    $t('applyReturn.refundReason1'),
    $t('applyReturn.refundReason2'),
    $t('applyReturn.refundReason3'),
    $t('applyReturn.refundReason4'),
    $t('applyReturn.refundReason5'),
    $t('applyReturn.refundReason6'),
    $t('applyReturn.refundReason7')
  ]
})
// 退款原因（未收到货）
const refundPriReasonArray = computed(() => {
  return [
    $t('applyReturn.refundReason1'),
    $t('applyReturn.refundReason2'),
    $t('applyReturn.refundReason7')
  ]
})
// 退款原因（总）
const refundReasonArray = computed(() => {
  return [
    $t('applyReturn.refundReason1'),
    $t('applyReturn.refundReason2'),
    $t('applyReturn.refundReason3'),
    $t('applyReturn.refundReason4'),
    $t('applyReturn.refundReason5'),
    $t('applyReturn.refundReason6'),
    $t('applyReturn.refundReason7'),
    '',
    $t('applyReturn.refundReason8')
  ]
})

// 订单模型 1虚拟商品订单
const orderMold = ref(0)
// 缓存中的货物状态
const isReceiverOfCach = ref(null)
let refundProdObj = {} // 订单数据
const orderItem = ref([]) // 订单项
let isLastProd = null
let isOnlyProd = false // 是否仅一个商品项（可退运费）
const refundType = ref(0)
const platformCouponAmount = ref(0)
const memberAmount = ref(0)
const goodsNum = ref(1) // 计数器数量
const showApplyRefund = ref(false) // 填写申请显隐
const refundSn = ref(route.query.refundSn) // 退款单号
// 是否需要核销
const needWriteOffs = ref(false)
// 最大可退款件数（虚拟商品：需要核销时展示）
const maxRefundPieces = ref(0)
const returnDetail = ref({}) // 退款详情信息
// 修改退款申请所需的标识
let upRefundId = 0
let upOrderId = 0
onMounted(() => {
  // 是否为虚拟商品订单
  orderMold.value = route.query.orderMold ? Number(route.query.orderMold) : 0
  // 从缓存中获取退款详情展示的货物状态
  isReceiverOfCach.value = localStorage.getItem('bbcIsReceiverOfCach')
  // 从缓存中拿到订单项
  refundProdObj = JSON.parse(localStorage.getItem('bbcRefundProdObj') || '{}')
  platformCouponAmount.value = refundProdObj.platformCouponAmount
  memberAmount.value = refundProdObj.memberAmount
  orderItem.value = refundProdObj.orderItem // 商品item
  upRefundId = refundProdObj.refundId // 修改退款信息时的退款id
  upOrderId = refundProdObj.orderId // 修改退款信息时的订单id
  isLastProd = orderItem.value[0].isLastProd // 是否最后一项
  isOnlyProd = refundProdObj.isOnlyProd // 是否仅一个商品项（可退运费）
  refundType.value = refundProdObj.refundType
  goodsNum.value = orderItem.value[0].prodCount // 商品数量
  // 订单项id
  orderRefundParam.orderItemId = refundProdObj.orderItem[0].orderItemId
  orderRefundParam.buyerMobile = refundProdObj.buyerMobile

  if (!returnDetail.value.refundSn && !refundSn.value) { // 退款编号为空时
    showApplyRefund.value = true // 填写申请
  }
  // 等待商家处理（修改和撤销按钮页）退款订单详情
  if (refundSn.value || !showApplyRefund.value) {
    getReturnDetail()
  }

  // 虚拟商品
  if (orderMold.value === 1) {
    // needWriteOffs是否需要核销
    needWriteOffs.value = refundProdObj.needWriteOffs
    // 最大可退件数（需要核销）
    if (needWriteOffs.value) {
      orderRefundParam.isReceiver = 1 // 核销不存在未收到货
      maxRefundPieces.value = refundProdObj.maxRefundPieces ? Number(refundProdObj.maxRefundPieces) : 0
    }
  }
  // 获取订单项商品数据（国际化时需要改变）
  queryProdInfo()
  // 设置网页标题
  document.title = $t('applyReturn.applyAfterSales')
})

// 赠品列表
const giveawayList = ref([])
/**
 * 商品信息
 */
const queryProdInfo = () => {
  http.get('/p/myOrder/orderDetail', {
    params: {
      orderNumber: route.query.orderNumber
    }
  }).then(({ data }) => {
    giveawayList.value = []
    orderItem.value = []
    // 要退的赠品商品项id数组
    orderRefundParam.giveawayItemIds = []
    // 单个退&有订单项id
    if (orderRefundParam.refundType === 2 &&
        orderRefundParam.orderItemId) {
      // 单个商品项
      const item = data.orderItemDtos.find(el => el.orderItemId === orderRefundParam.orderItemId) || null
      orderItem.value = item ? orderItem.value.concat(item) : []
      // 赠品列表
      giveawayList.value = orderItem.value[0].giveawayList ? orderItem.value[0].giveawayList : []
      // 赠品ids
      orderRefundParam.giveawayItemIds = giveawayList.value.map(el => el && el.orderItemId)
    } else {
      // 整单商品项
      orderItem.value = data.orderItemDtos
      // 收集每个订单项赠品列表里的赠品id
      orderItem.value.forEach(el => {
        if (el.giveawayList && el.giveawayList.length) {
          orderRefundParam.giveawayItemIds = orderRefundParam.giveawayItemIds.concat(el.giveawayList.map(el => el && el.orderItemId))
        }
      })
    }
    // 计算金额输入框初始默认价格
    getRefundAmount()
  })
}

// 被移除的赠品总额
let priceOfRemovedGiveaways = 0
/**
 * 点击移除（赠品）按钮重新计算可退总额
 */
const removeGiveaways = (index) => {
  // 赠品价值
  const giveawayAmount = giveawayList.value[index].giveawayAmount
  ElMessageBox.confirm(`${$t('prodDetail.removeGiftTip1') + giveawayAmount + $t('prodDetail.removeGiftTip2')}`, $t('chat.tips'), {
    confirmButtonText: $t('chat.confirm'),
    cancelButtonText: $t('chat.cancel'),
    type: 'warning'
  }).then(() => {
    // 实际总额
    const actualTotal = new Big(orderItem.value[0].actualTotal)
    // 商品总件数
    const prodCount = orderItem.value[0].prodCount
    // 已被移除的赠品总价
    const priceOfRemovedGiveawaysPar = priceOfRemovedGiveaways
    // 当前最大可退款金额 = 订单实际总额/商品总件数*当前退款件数-已被移除的赠品总价
    const curRefundAmount = actualTotal.div(prodCount).times(goodsNum.value).minus(priceOfRemovedGiveawaysPar)

    // 可退金额 = 当前最大可退款金额 - 当前点击移除的赠品价值
    const totalAmount = Number.parseFloat(curRefundAmount.minus(giveawayAmount).valueOf())

    // 当减去当前要移除的赠品价格所得值<=0时，不允许移除
    if (giveawayAmount > 0 && totalAmount <= 0) {
      ElMessage({
        message: $t('prodDetail.removeGiftTip3'),
        type: 'warning',
        duration: 2000,
        onClose: () => {
        }
      })
      return
    }

    // 已被移除的赠品总价
    priceOfRemovedGiveaways = new Big(giveawayAmount).plus(priceOfRemovedGiveaways).valueOf() || 0

    // 移除
    giveawayList.value.splice(index, 1)
    orderRefundParam.giveawayItemIds.splice(index, 1)

    // 计算退款金额
    getRefundAmount(totalAmount)
  }).catch(() => {

  })
}

/**
 * 处理价格样式
 */
const toPrice = (val) => {
  val = Number(val)
  if (!val) {
    val = 0
  }
  return (val.toFixed(2))
}

// 实际支付总积分
const totalRefundScore = ref(0)
const actualTotal = ref(Number(route.query.actualTotal)) // 实际总额
const refundAmount = ref(0) // （最多可退）退款金额
let totalRefundAmount = 0 // 可退总金额（含可退运费）
const showTransfee = ref(false) // 是否显示含运费提示
const status = ref(Number(route.query.status)) // 订单状态 1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败
const transfee = ref(route.query.transfee || 0) // 运费
/**
 * 计算金额输入框初始默认价格
 */
const getRefundAmount = (totalAmount) => {
  const newTransfee = new Big(transfee.value)
  let totalRefundScorePar = 0 //  totalRefundScore: 实际所有积分即可退换的所有积分
  orderItem.value.forEach(prodItem => {
    totalRefundScorePar += prodItem.useScore
  })
  totalRefundScore.value = totalRefundScorePar

  // 虚拟商品&需要核销：根据最多可退件数，计算最大可退金额
  if (orderMold.value === 1 && needWriteOffs.value) {
    const prodCount = orderItem.value[0].prodCount
    const actualTotalPar = orderItem.value[0].actualTotal
    Big.DP = 2
    Big.RM = 0
    actualTotal.value = new Big(actualTotalPar).times(maxRefundPieces.value).div(prodCount).valueOf()
    // 最多可退
    refundAmount.value = actualTotal.value
    // 记录可退款总金额
    totalRefundAmount = actualTotal.value
    return
  }

  // refundType退款单类型：1.整单退款,2.单个物品退
  if (orderRefundParam.refundType === 1) { // 整单退款
    actualTotal.value = refundProdObj.actualTotal
    const newActualTotal = new Big(actualTotal.value)
    if (status.value === 2 && transfee.value) { // 待发货且有运费
      refundAmount.value = newActualTotal.minus(newTransfee).valueOf()
      showTransfee.value = true
    } else { // 整单已发货（总额含运费且运费不减免）
      actualTotal.value = newActualTotal.minus(newTransfee).valueOf()
      refundAmount.value = actualTotal.value
      showTransfee.value = false
    }
  } else if (orderRefundParam.refundType === 2) { // 单个退
    actualTotal.value = totalAmount > 0 ? totalAmount : refundProdObj.orderItem[0].actualTotal
    const newActualTotal = new Big(actualTotal.value)
    refundAmount.value = actualTotal.value
    if (status.value === 2 && transfee && (isLastProd || isOnlyProd)) { // 待发货&&有运费&&(最后一个商品项||仅一个商品项)
      actualTotal.value = newActualTotal.valueOf()
      showTransfee.value = true
    } else {
      showTransfee.value = false
    }
  }

  // 记录可退款总金额
  totalRefundAmount = actualTotal.value
}

/**
 * 改变商品数量重新计算价格（数量加减）
 */
const changePordNum = (changeNum) => {
  const actualTotalPar = orderItem.value[0].actualTotal // 商品原始总额（不含运费）
  const prodCount = orderItem.value[0].prodCount // 商品原始总数
  const goodsNumPar = goodsNum.value + changeNum // 计数器商品总数
  // 被移除的赠品总数
  const priceOfRemovedGiveawaysPar = priceOfRemovedGiveaways || 0
  if (goodsNumPar < 1) {
    ElMessage({
      message: $t('applyReturn.returnedGoods'),
      type: 'error',
      duration: 1000
    })
    return
  }
  if (goodsNumPar > prodCount) {
    ElMessage({
      message: $t('applyReturn.refundReason9'),
      type: 'error',
      duration: 1500
    })
    return
  }
  Big.DP = 2
  Big.RM = 0
  // 当前最大可退款金额 = 实际总额/商品总数*当前退款数量-已被移除的赠品总价
  const amount = new Big(actualTotalPar).times(goodsNumPar).div(prodCount).minus(priceOfRemovedGiveawaysPar).valueOf()
  if (amount <= 0) {
    ElMessage({
      message: $t('applyReturn.canotReduce'),
      type: 'error',
      duration: 1500
    })
    return
  }

  goodsNum.value = goodsNumPar
  actualTotal.value = amount
  // 最多可退
  refundAmount.value = actualTotal.value
  totalRefundAmount = actualTotal.value
}

/**
 * 退款方式选择
 */
const returnType = (applyType) => {
  applyType === 1 ? orderRefundParam.applyType = 1 : orderRefundParam.applyType = 2
  if (applyType === 2) {
    orderRefundParam.isReceiver = 1
  }
}

/**
 * 货物状态选择
 */
const goodsStatus = (isReceiver) => {
  isReceiver === 1 ? orderRefundParam.isReceiver = 1 : orderRefundParam.isReceiver = 0
  orderRefundParam.buyerReason = ''
  orderRefundParam.buyerReasonStr = ''
}

const showMobileTips = ref(false) // 手机号码错误提示显隐
/**
 * 输入手机号input框过滤
 */
const resetMobileNumber = () => {
  // 失去焦点时
  // 如果手机号存在 && 位数不为0 && 不等于11 && 不符合规则 （当手机号大于0后，再判断规则是否正确）（待优化）
  showMobileTips.value = orderRefundParam.buyerMobile && orderRefundParam.buyerMobile.length > 0 &&
    (orderRefundParam.buyerMobile.length !== 11 || !util.checkPhoneNumber(orderRefundParam.buyerMobile))
}

const showReasonOptions = ref(false) // 退款原因选项
/**
 * 退款原因选项列表
 */
const selectReason = () => {
  showReasonOptions.value = true
}

const showSelectTips = ref(true) // 退款原因错误提示显隐
/**
 * 退款原因选择
 */
const returnReason = (e) => {
  orderRefundParam.buyerReason = e.target.dataset.idx
  orderRefundParam.buyerReasonStr = e.target.dataset.reason
  showSelectTips.value = false
  showReasonOptions.value = false
}

// 退款说明错误提示
const showBuyerDescErrTips = ref(false)
const checkBuyerDesc = () => {
  showBuyerDescErrTips.value = false
  if (!orderRefundParam.buyerDesc.trim()) {
    orderRefundParam.buyerDesc = ''
    showBuyerDescErrTips.value = true
  }
}

const showAmountTips = ref(false) // 退款金额错误提示显隐
// 失焦时校验金额是否输入正确
const resetActualTotal = () => {
  // 正则限制：正数（小数点后可以保留2位）
  const refundAmountReg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
  showAmountTips.value = false
  // 将输入框内容修改为两位小数
  actualTotal.value = Number(actualTotal.value.toString().replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1'))
  // 虚拟商品
  if (orderMold.value === 1 && (!refundAmountReg.test(actualTotal.value) || actualTotal.value < 0.01 || actualTotal.value > totalRefundAmount)) {
    showAmountTips.value = true
    return
  }

  // 积分为空时，输入框内容不为正数/小于0.01/大于最大退款数，就显示错误提示语
  if (!totalRefundScore.value && (!refundAmountReg.test(actualTotal.value) || actualTotal.value < 0.01 || actualTotal.value > totalRefundAmount)) {
    showAmountTips.value = true
  }
}

/**
 * 提交售后申请
 */
const applyRefund = util._debounce(() => {
  orderRefundParam.goodsNum = goodsNum.value
  orderRefundParam.refundAmount = parseFloat(actualTotal.value) || 0
  // 检查数据完整性
  orderRefundParam.refundAmount = parseFloat(actualTotal.value) || 0
  // 正则限制：正数（小数点后可以保留20位）
  const refundAmountReg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,20})?$/
  if (!orderRefundParam.buyerReason) { // 退款原因
    showSelectTips.value = true
    return
  } else if (!totalRefundScore.value && (!refundAmountReg.test(actualTotal.value) || actualTotal.value < 0.01 || actualTotal.value > totalRefundAmount)) {
    showAmountTips.value = true
    return
  }
  // 如果手机号存在 && 位数不为0 && 不等于11 && 不符合规则 （当手机号大于0后，再判断规则是否正确）（待优化）
  if (orderRefundParam.buyerMobile && orderRefundParam.buyerMobile.length > 0 && (orderRefundParam.buyerMobile.length !== 11 || !util.checkPhoneNumber(orderRefundParam.buyerMobile))) {
    // 手机号
    showMobileTips.value = true
  } else if (!orderRefundParam.buyerDesc.trim()) {
    // 退款说明
    showBuyerDescErrTips.value = true
  } else {
    if (orderRefundParam.isReceiver === 0) { // 未收到货
      // 未收到货需要转换一下原因
      orderRefundParam.buyerReason === 2 ? orderRefundParam.buyerReason = 6 : orderRefundParam.buyerReason = 0
    }
    // 整单退款移除 数量 和 订单项id
    if (orderRefundParam.refundType === 1) {
      orderRefundParam.orderItemId = undefined
      orderRefundParam.goodsNum = undefined
    }
    // 虚拟商品-需要核销，传最大可退货数量
    if (orderMold.value === 1 && needWriteOffs.value) {
      orderRefundParam.goodsNum = maxRefundPieces.value
    }
    applyOrderRefund(orderRefundParam)
  }
}, 1000)

// 请求申请退款接口
const applyOrderRefund = (orderRefundParam) => {
  // 清除缓存中的货物状态
  localStorage.removeItem('bbcIsReceiverOfCach')
  const url = upRefundId ? '/p/orderRefund/update_refund' : '/p/orderRefund/apply'
  const method = upRefundId ? 'PUT' : 'POST'
  if (upRefundId) {
    orderRefundParam.refundId = upRefundId
    orderRefundParam.orderId = upOrderId
  }
  http({
    url,
    method,
    data: orderRefundParam
  }).then(({ data }) => {
    refundSn.value = data // 退款编号
    // 将货物状态放进缓存
    localStorage.setItem('bbcIsReceiverOfCach', orderRefundParam.isReceiver)
    ElMessage({
      message: $t('applyReturn.applicationSuccessful'),
      duration: 1000,
      type: 'success'
    })
    setTimeout(() => {
      showApplyRefund.value = false
      router.push({ path: '/order-detail', query: { orderNumber: orderRefundParam.orderNumber } })
    }, 1000)
  })
}

const maxRefundAmount = ref(0)
// 退款项中是否使用了平台优惠 (使用了则不能修改退款金额)
const isUsedPlatformReduce = ref(false)
const photoFiles = ref([]) // 退款详情图片展示
const WaitProcessing = ref(false) // 等待商家处理显隐
const fillInLogistics = ref(false) // 填写物流显隐
const prodList = ref([])
/**
 * 请求退款详情信息
 */
const getReturnDetail = () => {
  http.get('/p/orderRefund/info?refundSn=' + refundSn.value).then(({ data }) => {
    let isUsedPlatformReducePar = false
    data.orderItems.forEach(item => {
      if (item.platformShareReduce && !isUsedPlatformReducePar) {
        isUsedPlatformReducePar = true
      }
    })
    maxRefundAmount.value = data.maxRefundAmount
    isUsedPlatformReduce.value = isUsedPlatformReducePar
    returnDetail.value = data
    // 详情页图片显示
    if (returnDetail.value.photoFiles) {
      photoFiles.value = (returnDetail.value.photoFiles).split(',')
    }
    if (refundSn.value && returnDetail.value.returnMoneySts === 1) { // 有退款编号且退款状态为1"买家申请"时
      WaitProcessing.value = true // 等待处理
    }
    if (refundSn.value && (returnDetail.value.returnMoneySts === 2 || returnDetail.value.returnMoneySts === 3) && returnDetail.value.applyType === 2) {
      // 退款状态为2"卖家接受"且退款类型为2“退货退款”时
      fillInLogistics.value = true
    }
    prodList.value = data.orderItems
    const orderItems = data.orderItems
    // 单个商品 && 有赠品时：
    if (orderItems.length === 1 && orderItems[0].giveawayList && orderItems[0].giveawayList.length) {
      prodList.value = [...orderItems, ...orderItems[0].giveawayList]
    }
  })
}

/**
 * 撤销申请
 */
const cancelApply = () => {
  ElMessageBox.confirm($t('applyReturn.refundReason11'), $t('applyReturn.tips'), {
    confirmButtonText: $t('determine'),
    cancelButtonText: $t('cancel'),
    type: 'warning'
  }).then(() => {
    http.put('/p/orderRefund/cancel', refundSn.value)
      .then(() => {
        ElMessage({
          message: $t('applyReturn.refundReason12'),
          duration: 1000,
          type: 'success'
        })
        setTimeout(() => {
          router.push({ path: '/user-center/uc-return' })
        }, 2000)
      })
  }).catch(() => {
  })
}

const showAdd = ref(false)
/**
 * 填写 || 修改物流信息
 */
const writeLogisticsMsg = () => {
  showAdd.value = true
}
/**
* 刷新回调
*/
const refreshChange = (visible) => {
  showAdd.value = visible
}

/**
 * 跳转商品详情
 */
const toProdDetail = (prodId) => {
  if (prodId) {
    const newPage = router.resolve({ path: '/detail', query: { prodId } })
    window.open(newPage.href, '_blank', 'noopener,noreferrer')
  }
}

const isModifyRefundAmount = ref(false) // 修改金额弹窗
const modifyAmount = ref('') // 修改金额
const refundAmountError = ref(false)
/**
 * 修改退款金额
 */
const modifyRefundAmount = () => {
  modifyAmount.value = ''
  refundAmountError.value = false
  isModifyRefundAmount.value = true
}

const handleAmountInput = () => {
  refundAmountError.value = false
  if (!modifyAmount.value || !modifyAmount.value.trim()) {
    modifyAmount.value = modifyAmount.value.trim()
    return
  }
  modifyAmount.value = checkInput(modifyAmount.value)
}

const checkInput = (num) => {
  if (num) {
    let tmpVal = num.replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}

const requestModify = () => {
  if (!modifyAmount.value || !modifyAmount.value.trim() || modifyAmount.value <= 0) {
    refundAmountError.value = true
    modifyAmount.value = modifyAmount.value.trim()
    return
  }
  if (Number.parseFloat(modifyAmount.value) > Number.parseFloat(maxRefundAmount.value)) {
    refundAmountError.value = true
    return
  }
  const param = {
    refundAmount: modifyAmount.value,
    refundSn: refundSn.value
  }
  http.put('/p/orderRefund/updateRefundAmount', param)
    .then(() => {
      ElMessage({
        message: $t('applyReturn.modifiedSuccessfully'),
        type: 'success',
        duration: 1000
      })
      isModifyRefundAmount.value = false
      refundAmountError.value = false
      refundAmount.value = ''
      getReturnDetail()
    })
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
<style lang="scss" scoped>
@use "../common/scss/user-center";
</style>
<style lang="scss" scoped>
@use "../common/scss/uc-edit";
</style>
